package com.chuanyang.driverh.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.chuanyang.driverh.amap.LocationEntity;

import java.util.ArrayList;
import java.util.List;


public class DBHistoryAddressContext {

	private MySqliteHistoryAddressHelper helper;
	
	public DBHistoryAddressContext(Context context){
		helper=new MySqliteHistoryAddressHelper(context);
	}

	/**
	 * 向数据库中插入一个地址
	 */
	public void insert(LocationEntity address){
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values=new ContentValues();
		values.put("building", address.getBuilding());
		values.put("address", address.getAddress());
		values.put("longitude", address.getLongitude());
		values.put("latitude", address.getLatitude());
		values.put("city", address.getCity());
//		values.put("city_id", address.getCity_id());

		db.delete("addresstable", "building = ?", new String[]{address.getBuilding()});
		db.insert("addresstable", null, values);  
		db.close();
		deleteFirstWhen10();
	}
	
	/**
	 * 每次向数据库插入数据 
	 * 1.插入前 删除数据库中已经存在的相同building的数据
	 * 2.插入后 判断一下数据库的数据的条数 超过10条 删除时间最初的一条
	 */
	private void deleteFirstWhen10(){
		SQLiteDatabase db = helper.getWritableDatabase();
		List<LocationEntity> list = getHistoryAddressList();
		if(list.size()>10){ //超过10条 删除第一条(时间最初的那条)
			db.delete("addresstable", "building = ?", new String[]{list.get(list.size()-1).getBuilding()});
		}
		db.close();
	}

	public void deleteall(){
		SQLiteDatabase db = helper.getWritableDatabase();

			db.delete("addresstable", "_id > ?", new String[]{"0"});

		db.close();
	}
	/**
	 * 获取保存的历史地址(每次通过地址检索点击选择的地址保存到数据库)
	 * @return
	 */
	public List<LocationEntity> getHistoryAddressList(){
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor curson=db.query("addresstable",null,null,null,null, null, "_id desc"); //_id 倒序
		List<LocationEntity> data=new ArrayList<LocationEntity>();
		LocationEntity locationEntity=null;
		while(curson.moveToNext()){  
			locationEntity=new LocationEntity();    
			locationEntity.setBuilding(curson.getString(1));
			locationEntity.setAddress(curson.getString(2));
			locationEntity.setLongitude(Double.parseDouble(curson.getString(3)));
			locationEntity.setLatitude(Double.parseDouble(curson.getString(4)));
			locationEntity.setCity(curson.getString(5));
//			locationEntity.setCity_id(curson.getString(6));
			data.add(locationEntity);
		}
		curson.close();   
		return data;
	}

	
}
